#!/bin/sh
PORTSDIR=/usr/ports
INDEX=$PORTSDIR/INDEX-`/usr/bin/uname -r | /usr/bin/cut -c 1`

cd $PORTSDIR && make fetchindex

if [ -z "$PACKAGES" ]; then
  PACKAGES=$PORTSDIR/packages
else
  PACKAGES=$PORTSDIR/packages-`/usr/bin/uname -r | /usr/bin/cut -c 1`
fi

TMPDIR=/tmp/`basename $0 | sed 's/\..*//'`
mkdir -p $TMPDIR
cd $PACKAGES/All
total=`ls | wc -l | awk '{print $1}'`
count=0
for pkg in *; do
  x=`echo $pkg | sed 's/\.tbz$//'`
  count=`expr $count + 1`
  echo $x ... $count/$total
  grep -q ^$x\| $INDEX
  if [ $? -ne 0 ]; then
    rm $PACKAGES/*/$x.tbz $TMPDIR/$x
    continue
  fi
  if [ ! -f "$TMPDIR/$x" ]; then
    mkdir -p $TMPDIR/$pkg && tar xf $pkg -C $TMPDIR/$pkg +CONTENTS && mv $TMPDIR/$pkg/+CONTENTS $TMPDIR/$x && rmdir $TMPDIR/$pkg &
  fi
done
wait

cd $TMPDIR
while true; do
  total=`ls | wc -l | awk '{print $1}'`
  count=0
  for x in *; do
    i=0
    #echo $x
    grep -q ^$x\| $INDEX
    if [ $? -ne 0 ]; then
      echo "$x not found in $INDEX, delete $PACKAGES/*/$x.tbz"
      rm $PACKAGES/*/$x.tbz $TMPDIR/$x
      continue
    fi
    for y in `cat $x | grep ^@pkgdep | awk '{print $2}'`; do
      #echo checking $y for $x
      if [ ! -f $PACKAGES/All/$y.tbz ]; then
        echo "$PACKAGES/All/$y.tbz not found, delete $PACKAGES/*/$x.tbz"
	rm $PACKAGES/*/$x.tbz $TMPDIR/$x
	i=1
	break
      fi
    done
    z=`cat $x | grep "^@comment ORIGIN:" | awk -F: '{print $2}'`
    if [ ! -d "$PORTSDIR/$z" ]; then
      echo "$PORTSDIR/$z not found, delete $PACKAGES/*/$x.tbz"
      rm $PACKAGES/*/$x.tbz $TMPDIR/$x
      continue
    fi
    if [ $i -eq 0 ]; then
      count=`expr $count + 1`
    fi
  done
  echo "total: $total"
  echo "count: $count"
  sleep 1
  if [ $total -eq $count ]; then break; fi
done

#rm -fr $TMPDIR
